package com.deep.deepenterpise.common.util;

import com.deep.deepenterpise.common.DrGson;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.time.Duration;
import java.util.Map;

/**
 * @author xyz
 * @version 1.0
 * @title DrOkHttpUtil
 * @description TODO DrHttpUtil工具类
 * @create 2024/4/16 12:47
 */
@Slf4j
public class DrOkHttpUtil {
    private static final OkHttpClient client = new OkHttpClient.Builder()
            // 设置连接超时时间
            .connectTimeout(Duration.ofSeconds(10))
            // 设置读取超时时间
            .readTimeout(Duration.ofSeconds(30))
            .build();

    private DrOkHttpUtil() {

    }

    /**
     * @return okhttp3.ResponseBody
     * @Auth xyz
     * @Desc //TODO get请求
     * @Time 10:50 2024/4/19
     * @Param [url]
     */
    public static String httpGet(String url) {
        Request request = new Request.Builder()
                .url(url)
                .get().build();
        return handleRequest(request);
    }

    /**
     * @return java.lang.String
     * @Auth xyz
     * @Desc //TODO get请求
     * @Time 11:05 2024/5/14
     * @Param [url, queryParams]
     */
    public static String httpGet(String url, Map<String, String> headers, Map<String, String> queryParams) {
        HttpUrl parse = HttpUrl.parse(url);
        if (parse == null) {
            log.info("[drGet调用失败]-------url格式错误：" + url);
            return null;
        }
        HttpUrl.Builder urlBuilder = parse.newBuilder();
        if (!CollectionUtils.isEmpty(queryParams)) {
            for (Map.Entry<String, String> param : queryParams.entrySet()) {
                urlBuilder.addQueryParameter(param.getKey(), param.getValue());
            }
        }
        Request.Builder requestBuilder = new Request.Builder().url(urlBuilder.build());
        if (!CollectionUtils.isEmpty(headers)) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        return handleRequest(requestBuilder.build());
    }

    /**
     * @return okhttp3.ResponseBody
     * @Auth xyz
     * @Desc //TODO post请求
     * @Time 11:28 2024/4/19
     * @Param [url, headers, queryParams, bodyParams]
     */
    public static String httpPost(String url, Map<String, String> headers, @NotNull Map<String, String> bodyParams) {
        return httpPost(url, headers, DrGson.toJSONString(bodyParams));
    }

    /**
     * @return java.lang.String
     * @Auth xyz
     * @Desc //TODO post请求
     * @Time 10:00 2024/5/14
     * @Param [url, headers, bodyJson]
     */
    public static String httpPost(String url, Map<String, String> headers, @NotNull String bodyJson) {
        HttpUrl parse = HttpUrl.parse(url);
        if (parse == null) {
            log.info("[drPost调用失败]-------url格式错误：" + url);
            return null;
        }

        HttpUrl.Builder urlBuilder = parse.newBuilder();

        Request.Builder requestBuilder = new Request.Builder().url(urlBuilder.build());

        if (!CollectionUtils.isEmpty(headers)) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        requestBuilder.post(RequestBody.create(bodyJson, JSON));

        return handleRequest(requestBuilder.build());
    }

    /**
     * @return java.lang.String
     * @Auth xyz
     * @Desc //TODO 处理请求
     * @Time 12:03 2024/4/19
     * @Param [request]
     */
    private static String handleRequest(Request request) {
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful() || response.body() == null) {
                log.info("[调用失败]-------" + "Unexpected code " + response);
                return null;
            }
            return response.body().string();
        } catch (IOException e) {
            log.info("[调用失败]-------" + DrCommonUtil.drGetStackTraceInfo(e));
            return null;
        }
    }
}
